#include "newbook.h"
#include "ui_newbook.h"
#include "dbbook.h"
#include "bmserver.h"

NewBook::NewBook(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::NewBook)
{
    ui->setupUi(this);
    m_posterPath.clear();

    QRegExpValidator *regexp = new QRegExpValidator(QRegExp(QString("^[0-9]{0,13}$")));
    ui->lineEdit_isbn->setValidator(regexp);
}

NewBook::~NewBook()
{
    delete ui;
}

void NewBook::on_bt_ok_clicked()
{
    QStringList strlist;
    QString str = ui->lineEdit_isbn->text().trimmed();
    if(str.isEmpty())
    {
        QMessageBox::information(this,"ISBN Infomation","    ISBN 必须被填写\t");
        return ;
    }
    strlist << str;
    str.clear();
    str = ui->lineEdit_Title->text().trimmed();
    if(str.isEmpty())
    {
        QMessageBox::information(this,"Title Infomation","   Book Name 必须被填写\t");
        return ;
    }
    strlist << str;
    str.clear();
    if(ui->comboBox_available->currentText() == "yes")
        strlist << tr("yes");
    else
        strlist << tr("no");
    strlist << tr("---");
    strlist << ui->lineEdit_author->text();
    strlist << ui->lineEdit_tag->text();
    strlist << ui->lineEdit_press->text();
    strlist << ui->doubleSpinBox_price->text();

    BMserver *p_tr = (BMserver *)this->parentWidget();
    str = strlist.at(0);
    if(p_tr->areadyhasSameData(str))
    {
        QMessageBox::information(this,"ISBN Infomation","数据库中此ISBN编号的书籍记录已存在，请仔细核对书籍的编号重新填写");
        return;
    }
    emit editfinished(strlist);

    this->close();
}



void NewBook::on_bt_cancel_clicked()
{
    this->close();
}


void NewBook::on_label_postimg_clicked()
{
    if(ui->lineEdit_isbn->text().isEmpty())
        return ;
    m_posterPath = QFileDialog::getOpenFileName(this, tr("Open File"),
                                                    ".",tr("Images (*.png *.jpg)"));
    QPixmap pixmap(m_posterPath);
    ui->label_postimg->setPixmap(pixmap.scaled(ui->label_postimg->size()));
}


void NewBook::savePost2File()
{
    if(m_posterPath.isEmpty())
        return;
    QImage img(m_posterPath);
    QString str = tr("./bookPost/")+ui->lineEdit_isbn->text().trimmed()+tr(".jpg");
    img.scaledToHeight(160).save(str);
    return ;
}
